package com.je.meta.service.upgrade.impl;

import com.je.common.base.DynaBean;
import com.je.common.base.upgrade.PackageResult;
import com.je.common.base.upgrade.UpgradeResourcesEnum;
import com.je.common.base.util.StringUtil;
import com.je.ibatis.extension.conditions.ConditionsWrapper;
import com.je.meta.util.enumUtil.TableTypeEnum;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 打包资源表
 */
@Service("upgradeTableDate")
public class UpgradeTableDate extends AbstractUpgradeMetaDate<PackageResult> {

    public UpgradeTableDate() {
        super(UpgradeResourcesEnum.TABLE);
    }

    @Override
    public void packUpgradeMetaDate(PackageResult packageResult, DynaBean upgradeBean) {
        List<String> tableIdList = getSourceIds(upgradeBean);
        if (tableIdList == null || tableIdList.size() == 0) {
            return;
        }
        packageResult.setProductTables(packageTable(tableIdList));
    }


    @Override
    public List<DynaBean> extractNecessaryData(PackageResult packageResult) {
        return packageResult.getProductTables();
    }

    private List<DynaBean> packageTable(List<String> tableIds) {
        List<DynaBean> tableBeanList = metaService.select("JE_CORE_RESOURCETABLE", ConditionsWrapper.builder()
                .in("JE_CORE_RESOURCETABLE_ID", tableIds));
        //排序，主表在前，子表在后,最后是视图
        List<DynaBean> sortTableList = sortResourceTable(tableBeanList);
        List<String> allParentIds = new ArrayList<>();
        for (DynaBean table : sortTableList) {
            String tableResourceId = table.getStr("JE_CORE_RESOURCETABLE_ID");
            //列
            List<DynaBean> tableColumns = metaService.select("JE_CORE_TABLECOLUMN",
                    ConditionsWrapper.builder().eq("TABLECOLUMN_RESOURCETABLE_ID", tableResourceId));
            table.set("tableColumns", tableColumns);
            //键
            List<DynaBean> tableKeys = metaService.select("JE_CORE_TABLEKEY",
                    ConditionsWrapper.builder().eq("TABLEKEY_RESOURCETABLE_ID", tableResourceId));
            table.set("tableKeys", tableKeys);
            if (!TableTypeEnum.VIEW.getValue().equals(table.getStr("RESOURCETABLE_TYPE"))) {
                //索引
                List<DynaBean> tableIndexs = metaService.select("JE_CORE_TABLEINDEX",
                        ConditionsWrapper.builder().eq("TABLEINDEX_RESOURCETABLE_ID", tableResourceId));
                table.set("tableIndexs", tableIndexs);
            } else {
                //视图关系
                List<DynaBean> viewCascades = metaService.select("JE_CORE_VIEWCASCADE",
                        ConditionsWrapper.builder().eq("JE_CORE_RESOURCETABLE_ID", table.getStr("JE_CORE_RESOURCETABLE_ID")));
                table.set("viewCascades", viewCascades);
            }
            //目录
            String SY_PARENTPATH = table.getStr("SY_PARENTPATH");
            List<String> currentParentIds = new ArrayList<>();
            for (String id : SY_PARENTPATH.split("/")) {
                if (!"ROOT".equals(id) && !allParentIds.contains(id)) {
                    allParentIds.add(id);
                    currentParentIds.add(id);
                }
            }
            table.set("parentList", metaService.select("JE_CORE_RESOURCETABLE", ConditionsWrapper.builder().in("JE_CORE_RESOURCETABLE_ID", currentParentIds)));
        }
        return sortTableList;
    }

    private List<DynaBean> sortResourceTable(List<DynaBean> tableBeanList) {
        List<DynaBean> parentTables = new ArrayList<>();
        List<DynaBean> childTables = new ArrayList<>();
        List<DynaBean> viewTables = new ArrayList<>();
        for (DynaBean dynaBean : tableBeanList) {
            if (TableTypeEnum.VIEW.getValue().equals(dynaBean.getStr("RESOURCETABLE_TYPE"))) {
                viewTables.add(dynaBean);
            } else {
                String parentTable = dynaBean.getStr("RESOURCETABLE_PARENTTABLECODES");
                if (StringUtil.isEmpty(parentTable)) {
                    parentTables.add(dynaBean);
                } else {
                    childTables.add(dynaBean);
                }
            }

        }
        if (parentTables.size() == tableBeanList.size()) {
            return sort(tableBeanList);
        }
        parentTables = sort(parentTables);
        if (childTables.size() == 1) {
            parentTables.addAll(childTables);
            parentTables.addAll(viewTables);
            return parentTables;
        }
        handleChildSort(parentTables, childTables);
        parentTables.addAll(viewTables);
        return parentTables;
    }

    private void handleChildSort(List<DynaBean> parentTables, List<DynaBean> childTables) {
        List<DynaBean> childs = new ArrayList<>();
        Map<String, String> map = parentTables.stream().collect(Collectors.toMap(p -> p.getStr("RESOURCETABLE_TABLECODE"), p -> p.getStr("JE_CORE_RESOURCETABLE_ID")));
        for (DynaBean child : childTables) {
            if (map.containsKey(child.getStr("RESOURCETABLE_PARENTTABLECODES"))) {
                parentTables.add(child);
            } else {
                childs.add(child);
            }
        }
        if (childs.size() == 0) {
            return;
        } else {
            //handleChildSort(parentTables,childs);
            parentTables.addAll(childs);
        }
    }


}
